<?php
namespace api\controllers;

use Yii;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;
use api\components\TransmitException;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use common\models\Message;

/**
 * 消息控制器
 * @author ZCY
 */
class MessageController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class'       => CompositeAuth::className(),
                'authMethods' => [
                    ['class' => HttpBearerAuth::className()],
                ],
                'optional'    => ['send-email', 'validatecode','send-sms'],
            ],
        ]);
    }
    
    
    /**
     * 发送短信
     */
    public function actionSendSms()
    {
        $params = Yii::$app->request->post();
        $model = new Message();
        $model->setScenario(Message::SCENARIO_SEND_SMS);
        if ($model->load(['Message' => $params])) {
            if ($result = $model->sendSms()) {
                return ['message' => '消息发送成功', 'data' => $result];
            }
        }
    }
    

    /**
     * 发送邮件
     */
    public function actionSendEmail()
    {
        $params = Yii::$app->request->post();
        $model = new Message();       
        $model->setScenario(Message::SCENARIO_SEND_EMAIL);
        if ($model->load(['Message' => $params])) {
            if ($result = $model->sendEmail()) {
                return ['message' => '邮件发送成功', 'data' => $result];
            }
        } 
    }

    /**
     * 校验验证码
     */
    public function actionValidatecode()
    {
        $params = Yii::$app->request->post();
        $model = new Message();
        $model->setScenario(Message::SCENARIO_VALIDATECODE);
        if ($model->load(['Message' => $params])) {
            list($flag, $info) = $model->validateCode();
            if ($flag) {
                return ['message' => '验证成功', 'data' => $info];
            } else {
                throw new TransmitException($info);
            }
        }
    }
}
